package sisi.agents;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CheckEvent;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Button;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.ports.Port;
import sisi.ports.PortController;
import sisi.suppliers.Portssupplier;
import sisi.suppliers.PortssupplierController;
import sisi.suppliers.SupplierWindow.SupplierPortsItemRenderer;

/**
 * AgentWindow.java - Controller class for <i>Agents window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 03/12/2013
 * 
 */
@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class AgentWindow extends Window implements 
				org.zkoss.zk.ui.ext.AfterCompose {
//window
private Window windowAgent, windowEditAgent;
private Textbox tbCerca;
private Listbox boxAgent, boxAgentPorts;
private List lista_Agent;
private boolean lNuovo;
private Toolbarbutton buttonSeleziona;
private ListModelList listModelList;
private Integer idSelezionato = 0;

protected Map<String, Object> args;
private Object AgentItem;
private Agent modAgent;
// edit
private Textbox address;
private Intbox agentid;
private Listbox agentvalut;
private Textbox city;
private Textbox companyname;
private Textbox contactname;
private Textbox contacttitle;
private Textbox country;
private Textbox email;
private Textbox fax;
private Textbox gsm;
private Textbox homepage;
private Textbox notes;
private Textbox phone;
private Intbox portid;
private Textbox postalcode;
private Textbox region;
private Checkbox req;
private Textbox reservednotes;
private Datebox dtup;
private Button buttonNuovoPort, buttonCancellaPort;

		public void onCreate$windowAgent(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N": tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		listModelList = new ListModelList();
		lista_Agent = new AgentController().getList(null);
		listModelList.addAll(lista_Agent);
		boxAgent.setModel(listModelList);
		boxAgent.setItemRenderer(new AgentItemRenderer());

		if (idSelezionato!=null && idSelezionato!=0){
		for (int i = 0; i < lista_Agent.size(); i++) {
			Agent record = (Agent)lista_Agent.get(i);
			if (record.getAgentid()==idSelezionato.intValue()){
				boxAgent.setSelectedIndex(i);
				break;
			}
		}
	}

}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}

	public void onClick$buttonCerca(Event event) {
		cerca();
	}


	private void cerca(){
		listModelList = new ListModelList();
		lista_Agent = new AgentController().getList(tbCerca.getValue());
		listModelList.addAll(lista_Agent);
		boxAgent.setModel(listModelList);
		boxAgent.setItemRenderer(new AgentItemRenderer());
	}

	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			seleziona();
		} else {
			modifica(false);
		}
	}

	public void onClick$buttonSeleziona(Event event) {

		seleziona();

}

	public void seleziona() {
		if (boxAgent.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oAgent = boxAgent.getSelectedItem().getAttribute("rigaAgent");
			String codiceSelezionato = ""+((Agent) oAgent).getAgentid();
			Sessions.getCurrent().setAttribute("codiceAgentSelezionato", codiceSelezionato);
			windowAgent.detach();
		}
	}

	public void onClick$buttonNuovo(Event event) {
		modifica(true);
	}

	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}

	private void modifica(boolean nuovo){
		try {

			int nIndex = boxAgent.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Selezionare una riga da modificare", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxAgent", boxAgent);
				Window finestraEditAgent = (Window) Executions.createComponents("/editAgent.zul", null, map);
				finestraEditAgent.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}

	public void onClick$buttonCancella(Event event) {
	// TODO Auto-generated method stub

	}

	public class AgentItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Agent) data).getAgentid()).setParent(li);
			new Listcell(""+((Agent) data).getCompanyname()).setParent(li);
			li.setAttribute("rigaAgent", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}


	// EDIT: NEW/MODIFY
	public void onCreate$windowEditAgent(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();

		boxAgent = (Listbox) args.get("boxAgent");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}

		if (!lNuovo) {
			AgentItem = boxAgent.getSelectedItem().getAttribute("rigaAgent");
			modAgent = new AgentController().refresh((Agent) AgentItem);
			AgentItem = modAgent;
			windowEditAgent.setTitle("Edit Agent");
			address.setValue(modAgent.getAddress());
			agentid.setValue(modAgent.getAgentid());
			
			if ((modAgent.getAgentvalut()!=null && !modAgent.getAgentvalut().isEmpty() ) ){
				agentvalut.setSelectedIndex(Integer.parseInt( modAgent.getAgentvalut() ) );				
			} else {
				agentvalut.setSelectedIndex(0);
			}

			city.setValue(modAgent.getCity());
			companyname.setValue(General.toUpperAncheNull(modAgent.getCompanyname()));
			contactname.setValue(General.toUpperAncheNull(modAgent.getContactname()));
			contacttitle.setValue(General.toUpperAncheNull(modAgent.getContacttitle()));
			country.setValue(General.toUpperAncheNull(modAgent.getCountry()));
			email.setValue(modAgent.getEmail());
			fax.setValue(modAgent.getFax());
			gsm.setValue(modAgent.getGsm());
			homepage.setValue(modAgent.getHomepage());
			notes.setValue(modAgent.getNotes());
			phone.setValue(modAgent.getPhone());
			portid.setValue(modAgent.getPortid());
			postalcode.setValue(modAgent.getPostalcode());
			region.setValue(General.toUpperAncheNull(modAgent.getRegion()));
			req.setChecked(modAgent.getReq());
			reservednotes.setValue(modAgent.getReservednotes());
			dtup.setValue( (java.util.Date) (modAgent.getDtup()));
			
			// agent ports
			ListModelList lmlAgentPorts = new ListModelList();
			List<Portsagent> lista_AgentPorts = new PortsagentsController().getListxIdAgent(agentid.getValue());
			lmlAgentPorts.addAll(lista_AgentPorts);
			boxAgentPorts.setModel(lmlAgentPorts);
			boxAgentPorts.setItemRenderer(new AgentPortsItemRenderer());	
			
			
		} else {
			windowEditAgent.setTitle("New Agent");
			
			// agent ports
			ListModelList lmlAgentPorts = new ListModelList();
			List<Portsagent> lista_AgentPorts = Collections.emptyList();
			lmlAgentPorts.addAll(lista_AgentPorts);
			boxAgentPorts.setModel(lmlAgentPorts);
			boxAgentPorts.setItemRenderer(new AgentPortsItemRenderer());	

			
		}
		
	}

	public void onClick$btnAnnulla(Event event){
		windowEditAgent.detach();
	}

	public void onClick$btnConferma(Event event){
			salvaRecord();
	}
		
		
	private void salvaRecord(){
		
		if (lNuovo){
			modAgent = new Agent();
		} else {

		}
		String testoMsg = "";

		modAgent.setAddress( General.toUpperAncheNull(address.getValue()));
		modAgent.setAgentid(agentid.getValue());	
		modAgent.setAgentvalut(""+ ( agentvalut.getSelectedIndex()==-1 ? "" : agentvalut.getSelectedIndex() ) );
		modAgent.setCity( General.toUpperAncheNull(city.getValue() ) );
		modAgent.setCompanyname(General.toUpperAncheNull(companyname.getValue()));
		modAgent.setContactname(General.toUpperAncheNull(contactname.getValue()));
		modAgent.setContacttitle(General.toUpperAncheNull(contacttitle.getValue()));
		modAgent.setCountry(General.toUpperAncheNull(country.getValue()));
		modAgent.setEmail(email.getValue());
		modAgent.setFax(fax.getValue());
		modAgent.setGsm(gsm.getValue());
		modAgent.setHomepage(homepage.getValue());
		modAgent.setNotes(notes.getValue());
		modAgent.setPhone(phone.getValue());
		modAgent.setPortid(portid.getValue());
		modAgent.setPostalcode(postalcode.getValue());
		modAgent.setRegion(General.toUpperAncheNull(region.getValue()));
		modAgent.setReq(req.isChecked());
		modAgent.setReservednotes(reservednotes.getValue());
		modAgent.setDtup( (dtup.getValue() != null ? (java.sql.Date) sisi.General.date2Sql(dtup.getValue()): null) );
		
		
		// cancello i ports abbinati all'agente e poi aggiungo quelli della lista
		if (modAgent.getAgentid()!=null){
			List<Portsagent> listaPSDaCancellare = new PortsagentsController().getListxIdAgent(modAgent.getAgentid());
			for (Portsagent portsagent : listaPSDaCancellare) {
				new PortsagentsController().remove(portsagent);
			}
		}
		
		ListModelList lmlPS = (ListModelList) boxAgentPorts.getListModel();
		int i = 1; 		
		if (lmlPS != null && lmlPS.size() > 0) {	
			for (Object object : lmlPS) {
				Portsagent pa = (Portsagent) object;
				pa.setAgentid(modAgent.getAgentid());
				pa.setAgentname(modAgent.getCompanyname());
				pa.setSeq(i++);
				new PortsagentsController().add(pa);
			}
		}


		if (lNuovo){
			new AgentController().add(modAgent);
			testoMsg = "New Agent: "+ General.trimNull( modAgent.getCompanyname() );
		} else {
			new AgentController().update(modAgent);
			testoMsg = "Updating Agent: "+ General.trimNull( modAgent.getCompanyname() );
		}

		General.showNotify( testoMsg, windowEditAgent);

		// aggiorna listbox

		if (lNuovo){
			ListModelList lml = (ListModelList) boxAgent.getListModel();
			lml.add(modAgent);
			boxAgent.setSelectedIndex(lml.indexOf(modAgent));
		} else {
			ListModelList lml = (ListModelList) boxAgent.getListModel();
			Object oAgentItem = boxAgent.getSelectedItem().getAttribute("rigaAgent");
			if (lml.indexOf(oAgentItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oAgentItem), modAgent);
			}
		}
		
		if (!lNuovo){
			windowEditAgent.detach();
		} else {
			lNuovo = false;
		}

		
	}

	
	public class AgentPortsItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			
			Portsagent pa = (Portsagent)data;
			
			
			Port port = new PortController().getPortxId(pa.getPortid());
						
			Integer seq = pa.getSeq();
			seq = (seq==null?0:seq);
			new Listcell(""+seq).setParent(li);
			new Listcell(""+port.getPortname()).setParent(li);
			new Listcell(""+pa.getCountry()).setParent(li);
			
			li.setAttribute("rigaAgentPorts", data);
		}
	}
	
	public void onClick$buttonNuovoPort(){
		
		if (agentid.getValue()==null){
			salvaRecord();
			agentid.setValue(modAgent.getAgentid());
		}
		
		Sessions.getCurrent().setAttribute("codicePortSelezionato", null);
		
		HashMap map = new HashMap();
		map.put("tastoSeleziona", "S");
		Window finestraSelPort = (Window) Executions.createComponents("/port.zul", null, map);
		finestraSelPort.doModal();
			
		String portSelected = (String)Sessions.getCurrent().getAttribute("codicePortSelezionato");
		if (portSelected!=null){
			Port port = new PortController().getPortxId(Integer.valueOf(portSelected));

			// faccio dei controlli e aggiungo la riga
			ListModelList lml = (ListModelList) boxAgentPorts.getListModel();
			boolean trovato = false;
			for (Object object : lml) {
				
				Portsagent pa = (Portsagent) object;
				if (pa.getPortid().equals( port.getId() ) ){
					trovato = true;
					new General().MsgBox("Port "+port.getPortname().trim()+" exist in this list. NOT added!", "Info");
					break;
				}
			}
			
			if( !trovato){
				Portsagent pa = new Portsagent();
				pa.setCountry(General.toUpperAncheNull(port.getCountry())); 
				pa.setPortid(port.getId());
				pa.setPortname(General.toUpperAncheNull(port.getPortname()));
				pa.setAgentid(agentid.getValue());
				pa.setAgentname(General.toUpperAncheNull(companyname.getValue()));
				pa.setSeq(boxAgentPorts.getItemCount()+1);
				lml.add(pa);
				boxAgentPorts.setSelectedIndex(boxAgentPorts.getItemCount()-1);
			}
		}
		
	}
	
	public void onClick$buttonCancellaPort(){
		int nIndex = boxAgentPorts.getSelectedIndex();

		if (nIndex == -1) { // nessuna riga selezionata
			Messagebox.show("Select a row to remove",
					"Information", Messagebox.OK, Messagebox.INFORMATION);
			return;
		} else {
			ListModelList lml = (ListModelList) boxAgentPorts.getListModel();
			lml.remove(nIndex);
			boxAgentPorts.setSelectedIndex(nIndex - 1);
		}
	}
	
}
//
// fine
